package com.example.zhangpeng.recyclerviewclick;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by zhangpeng on 2016/3/24.
 */
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements View.OnClickListener{
    @Override
    public void onClick(View v) {
        if(onRecyclerViewListner!=null){
            //注意这里使用getTag方法获取数据
            onRecyclerViewListner.setOnItemClickListner(v,(String)v.getTag());
        }

    }
    public void setOnItemClickListner(OnRecyclerViewListner onItemClickListner){
        this.onRecyclerViewListner=onItemClickListner;
    }
    private OnRecyclerViewListner onRecyclerViewListner;
    private String [] strings;
    public MyAdapter(String [] strings){
        this.strings=strings;
    }
    //define interface
    public static interface OnRecyclerViewListner{
           public void setOnItemClickListner(View v,String str);
       }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.layout1,parent,false);
        MyViewHolder myViewHolder=new MyViewHolder(view);
        view.setOnClickListener(this);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.textView.setText(strings[position]);
       //将数据保存在itemView的Tag中，以便点击时进行获取
        //setTag，就是给View添加一个额外的数据信息，进行数据关联
        //holder.view为final类型，即加载的view，在此为view= LayoutInflater.from(parent.getContext()).inflate(R.layout.layout1,parent,false)
        holder.itemView.setTag(strings[position]);
    }

    @Override
    public int getItemCount() {
        return strings==null ? 0: strings.length;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        TextView textView;
        public MyViewHolder(View itemView) {
            super(itemView);
            textView= (TextView) itemView.findViewById(R.id.tv_content);
        }
    }
}
